<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query">
              <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="dialogVisible = true">增加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <el-table :data="userlist" border style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="id" label="用户id" width="180"></el-table-column>
        <el-table-column prop="username" label="用户姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>

        <el-table-column prop="role_name" label="角色姓名"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope1">
            <!--定义一个插槽，该插槽必须放在template标签内-->
            <!-- 修改用户状态 -->
            <el-switch
              v-model="scope1.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(scope1.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="mg_state" label="操作" width="180px">
          <template slot-scope="scope1">
            <!-- size 按钮尺寸 -->
            <el-tooltip class="item" effect="dark" content="修改" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showUpdateDialog(scope1.row.id)"
              ></el-button>
            </el-tooltip>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope1.row.id)"
            ></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              <el-button type="warn" icon="el-icon-share" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <!-- <span class="demonstration">完整功能</span> -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[2, 4, 10, 15]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
      <!-- <el-button type="text" @click="dialogVisible = true">点击打开 Dialog</el-button> -->
      <!-- 增加用户 弹框-->
      <el-dialog title="增加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
        <span>
          <el-form
            :model="addUserForm"
             ref="addUserFormRef"
            :rules="addUserFormRules"
            label-width="100px"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addUserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="addUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户 -->
      <el-dialog title="修改用户" :visible.sync="updatedialogVisible" width="50%">
        <span>
          <el-form
            :model="updateUserForm"
            ref="updateUserFormRef"
           
            label-width="100px"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="updateUserForm.username"></el-input>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="updateUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="updateUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updatedialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateUser">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: "",

        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      total: 0,
      dialogVisible: false,
      updatedialogVisible:false,
      updateUserForm: {
        //不写默认是全部
        // id: "",
        // username: "",
        // password: "",
        // email: "",
        // mobile: ""
      },
      // 用户添加
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 用户添加表单验证规则
      addUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "用户名的长度在2～10个字",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getUserInfo();
  },
  methods: {
    async updateUser() {
      // 修改接口 邮箱和电话
      const { data: res } = await this.$http.put(
        "users/" + this.updateUserForm.id,
        {
          email: this.updateUserForm.email,
          mobile: this.updateUserForm.mobile
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("修改用户失败！");
      }
      this.$message.success("修改用户成功！");
      // 隐藏添加用户对话框
      this.updatedialogVisible = false;
      this.getUserInfo();
    },
    async showUpdateDialog(id) {
      //并且调用接口

      const { data: res } = await this.$http.get("users/" + id);
      console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error("删除用户失败！");
      }
      this.updateUserForm = res.data;
      this.updatedialogVisible = true;
      console.log(this.updateUserForm);
    },

    // 删除用户
    async removeUserById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status !== 200) return this.$message.error("删除用户失败！");
      this.$message.success("删除用户成功！");
      this.getUserInfo();
    },
    search() {
      this.getUserInfo();
    },
    async getUserInfo() {
      const { data: res } = await this.$http.get("/users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败！");
      }
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    addDialogClosed () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 添加用户
    async addUser() {
      // 提交请求前，表单预验证
      //   this.$refs.addUserFormRef.validate(async valid => {
      // console.log(valid)
      // 表单预校验失败
      // if (!valid) return;

      //   });
      const { data: res } = await this.$http.post("users", this.addUserForm);
      if (res.meta.status !== 201) {
        this.$message.error("添加用户失败！");
      }
      this.$message.success("添加用户成功！");
      // 隐藏添加用户对话框
      this.dialogVisible = false;
      this.getUserInfo();
    },
    handleSizeChange(pagesize) {
      console.log(`每页 ${pagesize} 条`);
      this.queryInfo.pagesize = pagesize;
      this.getUserInfo();
    },
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum;
      this.getUserInfo();
    },
    //修改用户状态
    async userStateChanged(userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      this.$message.success("更新用户状态成功！");
    }
  }
};
</script>

<style>
</style>